//*- coding = utf-8 -*-
//@Time : 2022-11-20 23:49
//@Author : 沉默小管
//@File : index.js
//@web  : golangblog.blog.csdn.net
//@Software: WebStorm
import Redis from 'ioredis/built/Redis';
import { redisConfig } from '@/utils/config';

let num:number = 0;
const redisIndex = [];//记录redis实例索引
const redisList:Redis[] = [];//用于存储redis实例

export class RedisInstance {

  private readonly method:string;  //调用的方法名
  private readonly db:number;      //仓库数量
  private client:Redis;
  constructor(method:string='vueCms_xg',db:number=0) {
    this.method = method
    this.db = db
    this.client = this.initRedis(method,db)
  }

  //初始化redis
  private initRedis(method:string,db:number=0){
    const isExist = redisIndex.some(x=>x===db)
    if(!isExist){
      console.log(`[Redis ${db}]来自 ${method} 方法调用, Redis 实例化了 ${++num} 次 `);
      redisList[db] = new Redis({...redisConfig,db})
      redisList[db].on('error', (err) => console.log('Redis cluster Error', err));
      redisList[db].on('connect', () => console.log('redis连接成功'));
      redisIndex.push(db)
    }else{
      console.log(`[Redis ${db}]来自 ${method} 方法调用`);
    }
    return redisList[db]

  }

  /**
   * @Description: 封装设置redis缓存的方法
   * @param key {String} key值
   * @param value {String} key的值
   * @param seconds {Number} 过期时间
   * @return: Promise<any>
   */
  public async set(key: string, value: any, seconds?: number): Promise<any> {
    value = JSON.stringify(value);
    if (!this.client) {
      this.client = await this.initRedis(this.method,this.db)
    }
    if (!seconds) {
      await this.client.set(key, value, (err:Error, data) => {
        // 为key 设定一个时长 单位为S
        this.client.expire(key, 3600000)
        if (err) {
          console.log(err);
        }
        return data //成功会返回ok
      });
    } else {
      await this.client.set(key, value, 'EX', seconds);
    }
  }


  /**
   * @Description: 设置获取redis缓存中的值
   * @param key {String}
   */
  public async get(key: string): Promise<any> {
    if (!this.client) {
      this.client = await this.initRedis(this.method,this.db)
    }

    let data = await this.client.get(key);

    if (data) {
      return JSON.parse(data);
    } else {
      return null;
    }
  }

  /**
   * @Description: 根据key删除redis缓存数据
   * @param key {String}
   * @return:
   */
  public async del(key: string): Promise<any> {
    if (!this.client) {
      this.client = await this.initRedis(this.method,this.db)
    }

    await this.client.del(key);
  }

  /**
   * @Description: 清空redis的缓存
   * @return:
   */
  public async clearRedisData(): Promise<any> {
    if (!this.client) {
      this.client = await this.initRedis(this.method,this.db)
    }

    await this.client.flushall();
  }


}